package com.example.demo.controller;

import com.example.demo.DTO.Login_DTO;
import com.example.demo.Server.LoginServer;


import com.example.demo.entity.User;
import com.example.demo.result.Result;
import com.example.demo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.properties.JwtProperties;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Login_Controller {
@Autowired
    private LoginServer loginServer;

    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/User_login")
    public Result<User> login(@RequestBody Login_DTO login_dto) {
        // 这里可以添加登录逻辑，例如验证账号和密码
        User user = User.builder()
                .account(login_dto.getAccount())
                .password(login_dto.getPassword())
                .build();
        User user_after = loginServer.login(user);


        //登入成功生成并下发令牌
        if(user_after!=null){
            Map<String, Object> claims=new HashMap<>();
            claims.put("id",user_after.getUserID());
            claims.put("role", "USER"); // 添加角色标识

            String jwt = JwtUtils.generateJwt(claims);
            user_after.setToken(jwt);
            return Result.success(user_after);
        }
        //登入失败返回错误信息


        if(user_after != null){
            return Result.success(user_after);
        }else{
            return Result.error("登录失败");
        }


    }
    @PostMapping("/User_Register")
    public Result register(@RequestBody User user)
    {
        loginServer.register(user);


        return Result.success();
    }

}
